# Release Build Validation and Fix Script
# Checks and fixes issues that may cause debug DLL dependencies

param(
    [switch]$Fix = $false,
    [switch]$Verbose = $false
)

Write-Host "========== Flutter Release Build Check Tool ==========" -ForegroundColor Cyan
Write-Host "Check Time: $(Get-Date)" -ForegroundColor Gray
Write-Host ""

# Store check results
$issues = @()
$warnings = @()
$fixes = @()

function Write-Check {
    param($Message, $Status, $Details = "")
    
    $symbol = switch ($Status) {
        "PASS" { "[PASS]"; break }
        "FAIL" { "[FAIL]"; break }
        "WARN" { "[WARN]"; break }
        "INFO" { "[INFO]"; break }
    }
    
    $color = switch ($Status) {
        "PASS" { "Green"; break }
        "FAIL" { "Red"; break }
        "WARN" { "Yellow"; break }
        "INFO" { "Cyan"; break }
    }
    
    Write-Host "$symbol $Message" -ForegroundColor $color
    if ($Details -and $Verbose) {
        Write-Host "   $Details" -ForegroundColor Gray
    }
}

function Test-FileContains {
    param($FilePath, $Pattern, $Description)
    
    if (Test-Path $FilePath) {
        $content = Get-Content $FilePath -Raw
        if ($content -match $Pattern) {
            return $true
        }
    }
    return $false
}

# 1. Check project root directory
Write-Host "1. Checking project structure..." -ForegroundColor Yellow

if (-not (Test-Path "pubspec.yaml")) {
    Write-Check "Current directory is not Flutter project root" "FAIL"
    $issues += "Please run this script in Flutter project root directory"
    exit 1
} else {
    Write-Check "Flutter project root directory check" "PASS"
}

# 2. Check CMakeLists.txt configuration
Write-Host "`n2. Checking Windows CMake configuration..." -ForegroundColor Yellow

$cmakeFile = "windows\CMakeLists.txt"
if (Test-Path $cmakeFile) {
    $cmakeContent = Get-Content $cmakeFile -Raw
    
    # Check default build type
    if ($cmakeContent -match 'CMAKE_BUILD_TYPE\s+"Debug"') {
        Write-Check "CMakeLists.txt defaults to Debug mode" "FAIL"
        $issues += "CMakeLists.txt has Debug as default build type"
        
        if ($Fix) {
            $newContent = $cmakeContent -replace 'CMAKE_BUILD_TYPE\s+"Debug"', 'CMAKE_BUILD_TYPE "Release"'
            Set-Content $cmakeFile -Value $newContent -Encoding UTF8
            Write-Check "Fixed CMakeLists.txt default build type to Release" "INFO"
            $fixes += "Fixed CMakeLists.txt default build type"
        }
    } elseif ($cmakeContent -match 'CMAKE_BUILD_TYPE\s+"Release"') {
        Write-Check "CMakeLists.txt defaults to Release mode" "PASS"
    } else {
        Write-Check "CMAKE_BUILD_TYPE not explicitly set" "WARN"
        $warnings += "Recommend explicitly setting Release as default build type in CMakeLists.txt"
    }
} else {
    Write-Check "Cannot find windows/CMakeLists.txt" "FAIL"
    $issues += "Windows platform CMakeLists.txt file is missing"
}

# 3. Check existing build artifacts
Write-Host "`n3. Checking existing build artifacts..." -ForegroundColor Yellow

$buildDir = "build\windows\x64\runner"
if (Test-Path $buildDir) {
    # Check Debug directory
    $debugDir = "$buildDir\Debug"
    if (Test-Path $debugDir) {
        Write-Check "Found Debug build directory" "WARN"
        $warnings += "Debug build directory exists, recommend cleanup"
        
        if ($Fix) {
            Remove-Item -Recurse -Force $debugDir -ErrorAction SilentlyContinue
            Write-Check "Removed Debug build directory" "INFO"
            $fixes += "Removed Debug build directory"
        }
    }
    
    # Check for debug DLLs in Release directory
    $releaseDir = "$buildDir\Release"
    if (Test-Path $releaseDir) {
        $debugDlls = Get-ChildItem -Path $releaseDir -Filter "*D.dll" -Recurse -ErrorAction SilentlyContinue
        if ($debugDlls.Count -gt 0) {
            Write-Check "Found debug DLLs in Release directory" "FAIL"
            $issues += "Release build directory contains debug version DLLs"
            
            foreach ($dll in $debugDlls) {
                Write-Host "   - $($dll.Name)" -ForegroundColor Red
            }
            
            if ($Fix) {
                foreach ($dll in $debugDlls) {
                    Remove-Item $dll.FullName -Force -ErrorAction SilentlyContinue
                }
                Write-Check "Removed debug version DLLs" "INFO"
                $fixes += "Removed debug version DLL files"
            }
        } else {
            Write-Check "No debug DLLs found in Release directory" "PASS"
        }
    }
} else {
    Write-Check "No build directory found" "INFO" "This is normal if this is first time building"
}

# 4. Check onnxruntime build configuration
Write-Host "`n4. Checking onnxruntime build configuration..." -ForegroundColor Yellow

$onnxBuildDir = "onnxruntime\build"
if (Test-Path $onnxBuildDir) {
    # Check CMakeCache.txt for build type
    $cmakeCache = "$onnxBuildDir\CMakeCache.txt"
    if (Test-Path $cmakeCache) {
        $cacheContent = Get-Content $cmakeCache -Raw
        if ($cacheContent -match "CMAKE_BUILD_TYPE:STRING=Debug") {
            Write-Check "ONNX Runtime configured for Debug mode" "FAIL"
            $issues += "ONNX Runtime using Debug build type"
            
            if ($Fix) {
                Write-Check "Cleaning ONNX Runtime build cache..." "INFO"
                Remove-Item -Recurse -Force $onnxBuildDir -ErrorAction SilentlyContinue
                $fixes += "Cleaned ONNX Runtime Debug build cache"
            }
        } elseif ($cacheContent -match "CMAKE_BUILD_TYPE:STRING=Release") {
            Write-Check "ONNX Runtime configured for Release mode" "PASS"
        }
    }
    
    # Check for debug DLLs in output
    $debugDlls = Get-ChildItem -Path $onnxBuildDir -Filter "*D.dll" -Recurse -ErrorAction SilentlyContinue
    if ($debugDlls.Count -gt 0) {
        Write-Check "ONNX Runtime build contains debug DLLs" "FAIL"
        $issues += "ONNX Runtime build artifacts contain debug version DLLs"
        
        if ($Fix) {
            Remove-Item -Recurse -Force $onnxBuildDir -ErrorAction SilentlyContinue
            Write-Check "Cleaned ONNX Runtime build directory" "INFO"
            $fixes += "Cleaned ONNX Runtime build directory"
        }
    }
} else {
    Write-Check "ONNX Runtime not yet built" "INFO"
}

# 5. Check DLL files in assets
Write-Host "`n5. Checking DLL files in assets..." -ForegroundColor Yellow

$assetsDllDir = "assets\dlls"
if (Test-Path $assetsDllDir) {
    $debugDlls = Get-ChildItem -Path $assetsDllDir -Filter "*D.dll" -ErrorAction SilentlyContinue
    if ($debugDlls.Count -gt 0) {
        Write-Check "Found debug DLLs in assets/dlls" "FAIL"
        $issues += "assets directory contains debug version DLLs"
        
        foreach ($dll in $debugDlls) {
            Write-Host "   - $($dll.Name)" -ForegroundColor Red
        }
        
        if ($Fix) {
            foreach ($dll in $debugDlls) {
                Remove-Item $dll.FullName -Force -ErrorAction SilentlyContinue
            }
            Write-Check "Removed debug DLLs from assets" "INFO"
            $fixes += "Removed debug version DLLs from assets"
        }
    } else {
        Write-Check "assets/dlls directory is clean" "PASS"
    }
} else {
    Write-Check "assets/dlls directory does not exist" "INFO"
}

# 6. Summary report
Write-Host "`n========== Check Results Summary ==========" -ForegroundColor Cyan

Write-Host "`nIssues ($($issues.Count)):" -ForegroundColor Red
foreach ($issue in $issues) {
    Write-Host "[FAIL] $issue" -ForegroundColor Red
}

Write-Host "`nWarnings ($($warnings.Count)):" -ForegroundColor Yellow
foreach ($warning in $warnings) {
    Write-Host "[WARN] $warning" -ForegroundColor Yellow
}

if ($Fix -and $fixes.Count -gt 0) {
    Write-Host "`nApplied Fixes ($($fixes.Count)):" -ForegroundColor Green
    foreach ($fixItem in $fixes) {
        Write-Host "[FIXED] $fixItem" -ForegroundColor Green
    }
}

# 7. Recommended next steps
Write-Host "`n========== Recommended Next Steps ==========" -ForegroundColor Cyan

if ($issues.Count -gt 0) {
    Write-Host "Execute these steps immediately:" -ForegroundColor Yellow
    Write-Host "1. Run: .\check_release_build.ps1 -Fix (auto-fix issues)" -ForegroundColor White
    Write-Host "2. Clean project: flutter clean" -ForegroundColor White
    Write-Host "3. Rebuild: flutter build windows --release" -ForegroundColor White
    Write-Host "4. Recheck: .\check_release_build.ps1" -ForegroundColor White
} elseif ($warnings.Count -gt 0) {
    Write-Host "Recommended actions:" -ForegroundColor Yellow
    Write-Host "1. Clean project: flutter clean" -ForegroundColor White
    Write-Host "2. Rebuild: flutter build windows --release" -ForegroundColor White
} else {
    Write-Host "Project configuration is correct, ready for Release build" -ForegroundColor Green
    Write-Host "Run: flutter build windows --release" -ForegroundColor White
}

Write-Host "`n========== Check Complete ==========" -ForegroundColor Cyan
Write-Host "For detailed information, use -Verbose parameter" -ForegroundColor Gray

# Return appropriate exit code
if ($issues.Count -gt 0) {
    exit 1
} elseif ($warnings.Count -gt 0) {
    exit 2
} else {
    exit 0
}
